package com.quick.controller.monitor;


import com.quick.common.annotation.Log;
import com.quick.common.constants.CacheConstants;
import com.quick.common.core.controller.BaseController;
import com.quick.common.core.domain.ApiResponse;
import com.quick.common.core.domain.LoginUser;
import com.quick.common.enums.BusinessTypeEnum;
import com.quick.common.redis.RedisCache;
import com.quick.common.utils.StringUtils;
import com.quick.system.domain.SysUserOnline;
import com.quick.system.service.SysUserOnlineService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 在线用户监控
 *
 * @Author: 吃素不吃肉
 * @Date: Tue Jul 25 14:14:44 CST 2023
 */
@RestController
@RequestMapping("/monitor/online")
public class SysUserOnlineController extends BaseController {
    @Autowired
    private SysUserOnlineService sysUserOnlineService;

    @Autowired
    private RedisCache redisCache;

    @PreAuthorize("@ps.hasPermission('monitor:online:list')")
    @GetMapping("/list")
    public ApiResponse list(String ipaddr, String userName) {
        Collection<String> keys = redisCache.keys(CacheConstants.LOGIN_TOKEN_KEY + "*");
        List<SysUserOnline> userOnlineList = new ArrayList<>();
        for (String key : keys) {
            LoginUser user = redisCache.getCacheObject(key);
            if (StringUtils.isNotEmpty(ipaddr) && StringUtils.isNotEmpty(userName)) {
                userOnlineList.add(sysUserOnlineService.selectOnlineByInfo(ipaddr, userName, user));
            } else if (StringUtils.isNotEmpty(ipaddr)) {
                userOnlineList.add(sysUserOnlineService.selectOnlineByIpaddr(ipaddr, user));
            } else if (StringUtils.isNotEmpty(userName)) {
                userOnlineList.add(sysUserOnlineService.selectOnlineByUserName(userName, user));
            } else {
                userOnlineList.add(sysUserOnlineService.loginUserToUserOnline(user));
            }
        }
        return total(userOnlineList);
    }

    /**
     * 强退用户
     */
    @PreAuthorize("@ps.hasPermission('monitor:online:forceLogout')")
    @Log(title = "在线用户", businessType = BusinessTypeEnum.FORCE)
    @DeleteMapping("/{tokenId}")
    public ApiResponse forceLogout(@PathVariable String tokenId) {
        redisCache.deleteObject(CacheConstants.LOGIN_TOKEN_KEY + tokenId);
        return success();
    }
}
